import { useRequest } from "@/hooks/use-request";
import { antdUtils } from "@/utils/antd";
import { t } from "@/utils/i18n";
import { useMount } from "ahooks";
import {
  Button,
  Popconfirm,
  Space,
  Table,
  TablePaginationConfig,
  Tag,
} from "antd";
import React, { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import NewAndEditProject from "./new-edit-project";
import projectService, { ProjectBean } from "./service";

const Project: React.FC = () => {
  // const { currentUser } = useUserStore();
  const navigate = useNavigate();
  const [dataSource, setDataSource] = useState<ProjectBean[]>([]);
  const [createVisible, setCreateVisible] = useState(false);
  const [editData, setEditData] = useState<null | ProjectBean>(null);
  const { loading, runAsync: getProjectsByPage } = useRequest(
    projectService.getProjectByPage,
    { manual: true }
  );
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 8,
  });

  const { runAsync: deleteProject } = useRequest(projectService.deleteProject, {
    manual: true,
  });

  const deleteP = async (id?: string) => {
    if (!id || id.length === 0 || id === "") {
      return;
    }
    const [error] = await deleteProject(id);
    if (error) {
      antdUtils.message?.error("删除失败 " + error);
      return;
    }
    antdUtils.message?.success("删除成功");
    getPorjects();
  };

  const cancelHandle = () => {
    setCreateVisible(false);
    setEditData(null);
  };

  const saveHandle = () => {
    setCreateVisible(false);
    setEditData(null);
    getPorjects();
  };

  const getPorjects = async () => {
    const { current, pageSize } = pagination || {};

    const [error, data] = await getProjectsByPage({
      current,
      pageSize,
    });
    if (!error) {
      setDataSource(
        data.data.map((item: any) => {
          item.users = item.users ? JSON.parse(item.users) : [];
          item.timeNode = item.timeNode ? JSON.parse(item.timeNode) : [];
          return item;
        })
      );
      setPagination((prev: any) => ({
        ...prev,
        total: data.total,
      }));
    }
  };

  const tabChangeHandle = (tablePagination: TablePaginationConfig) => {
    setPagination(tablePagination);
  };

  useMount(() => {
    // fetch(`http://192.168.100.200:8080/project/plan/getAll`, {
    //   method: "POST",
    // })
    //   .then((res) => res.text())
    //   .then((res) => {
    //     const data = JSON.parse(res);
    //     if (data.state === "ok") {
    //       data.result.forEach(async (e: any) => {
    //         e.notes = JSON.stringify(e.notes);
    //         await request.post<any>("/api/plan", e);
    //       });
    //     }
    //   })
    //   .catch((error) => {})
    //   .finally(() => {});
    // fetch(`http://192.168.100.200:8080/users/getall`, {
    //   method: "GET",
    // })
    //   .then((res) => res.text())
    //   .then((res) => {
    //     const data = JSON.parse(res);
    //     if (data.state === "ok") {
    //       console.log("resultresult", data.result);
    //       data.result.forEach(async (e: any) => {
    //         console.log("11111111", e);
    //         const a: any = {};
    //         a.id = e._id;
    //         a.userName = e.username;
    //         a.nickName = e.nickname;
    //         a.password = e.password;
    //         if (a.userName != "admin") {
    //           await request.post<any>("/api/user", a);
    //         }
    //       });
    //     }
    //   })
    //   .catch((error) => {})
    //   .finally(() => {});
    // fetch(`http://192.168.100.200:8080/project/all`, {
    //   method: "GET",
    // })
    //   .then((res) => res.text())
    //   .then((res) => {
    //     const data = JSON.parse(res);
    //     if (data.state === "ok") {
    //       console.log("resultresult", data.result);
    //       data.result.forEach(async (e: any) => {
    //         const ulist = e.users.map((u: any) => {
    //           return { id: u._id, nickName: u.nickname };
    //         });
    //         const tlist = e.timeNode.map((t: any) => {
    //           return {
    //             id: t._id,
    //             info: t.info,
    //             operator: t.operator,
    //             state: t.state,
    //             time: t.time,
    //           };
    //         });
    //         const plist = e.plans?.map((p: any) => {
    //           return {
    //             id: p._id,
    //             planids: p.planids,
    //             userid: p.userid,
    //           };
    //         });
    //         e.users = ulist;
    //         e.timeNode = tlist;
    //         e.plans = plist;
    //         e.id = e._id;
    //         console.log("11111111", e);
    //         await projectService.addProject(e);
    //       });
    //     }
    //   })
    //   .catch((error) => {})
    //   .finally(() => {});
  });

  useEffect(() => {
    getPorjects();
  }, [pagination.size, pagination.current]);

  const columns: any[] = useMemo(
    () => [
      {
        title: "项目名",
        dataIndex: "name",
        key: "name",
        width: 200,
        fixed: "left",
      },
      {
        title: "编号",
        dataIndex: "number",
        key: "number",
        width: 150,
      },
      {
        title: "开始时间",
        dataIndex: "startTime",
        key: "startTime",
        width: 125,
      },
      {
        title: "预计结束时间",
        dataIndex: "endTime",
        key: "endTime",
        width: 125,
      },
      {
        title: "参与人员",
        dataIndex: "users",
        key: "users",
        width: 400,
        render: (_: any, item: any) => (
          <>
            {item.users?.map((user: any) => {
              return <Tag key={user.id}>{user.nickName}</Tag>;
            })}
          </>
        ),
      },
      {
        title: "描述",
        dataIndex: "describe",
        key: "describe",
        width: 400,
      },
      {
        title: "备注",
        dataIndex: "notes",
        key: "notes",
        width: 400,
      },
      {
        title: "操作",
        key: "_id",
        align: "center",
        width: 250,
        fixed: "right",
        render: (_: any, item: ProjectBean) => (
          <Space>
            <Button
              size="small"
              onClick={(e: any) => {
                e.stopPropagation();
                navigate(`/project/timenode/${item.id}`);
              }}
            >
              {t("ImportantNodes") /**重要节点 */}
            </Button>
            <Button
              size="small"
              onClick={(e: any) => {
                e.stopPropagation();
                setEditData(item);
                setCreateVisible(true);
              }}
            >
              {t("wXpnewYo") /**编辑 */}
            </Button>
            <Popconfirm
              title={t("nlZBTfzL") /** 确认删除这条数据？*/}
              onConfirm={(e: any) => {
                e.stopPropagation();
                deleteP(item.id);
              }}
              onCancel={(e: any) => {
                e.stopPropagation();
              }}
              okText={t("confirm") /**确认 */}
              cancelText={t("cancel") /**取消 */}
            >
              <Button
                size="small"
                type="dashed"
                danger
                onClick={(e: any) => {
                  e.stopPropagation();
                }}
              >
                {t("HJYhipnp") /**删除 */}
              </Button>
            </Popconfirm>
          </Space>
        ),
      },
    ],
    []
  );

  return (
    <div className="">
      <Button
        className="mb-[12px]"
        type="primary"
        onClick={() => {
          setCreateVisible(true);
        }}
        // v-auth="menu:create"
      >
        {t("VjwnJLPY") /** 新建 */}
      </Button>
      <Table
        columns={columns}
        dataSource={dataSource}
        rowKey="id"
        loading={loading}
        pagination={pagination}
        onChange={tabChangeHandle}
        scroll={{ x: "100%", y: "auto" }}
        onRow={(item) => {
          return {
            onClick: () => {
              navigate(`/project/plan`, { state: item });
            },
          };
        }}
      />
      <NewAndEditProject
        onSave={saveHandle}
        onCancel={cancelHandle}
        visible={createVisible}
        editData={editData}
      />
    </div>
  );
};

export default Project;
